<template>
  <el-dialog
    v-model="visible"
    title="数据质量评估报告"
    width="80%"
    top="5vh"
    :close-on-click-modal="false"
    :destroy-on-close="true"
  >
    <div class="assessment-container">
      <div class="header-controls">
        <el-select v-model="selectedDataSource" placeholder="请选择要评估的数据源" @change="runAssessment">
          <el-option label="GNSS监测点 ZD01 (最近24小时)" value="gnss_zd01_24h"></el-option>
          <el-option label="降雨量监测站 YL03 (最近7天)" value="rain_yl03_7d"></el-option>
          <el-option label="地下水位 SW05 (最近7天)" value="water_sw05_7d"></el-option>
        </el-select>
      </div>

      <div v-if="assessmentData" class="report-content">
        <el-skeleton :loading="loading" animated>
          <template #template>
            <div style="display: flex; gap: 20px;">
              <div style="width: 25%;">
                <el-skeleton-item variant="h3" style="width: 100%; margin-bottom: 20px;" />
                <el-skeleton :rows="5" />
              </div>
              <div style="width: 75%;">
                 <el-skeleton-item variant="image" style="width: 100%; height: 300px; margin-bottom: 20px;" />
                 <el-skeleton :rows="4" />
              </div>
            </div>
          </template>
          
          <template #default>
            <el-row :gutter="20">
              <el-col :span="7">
                <el-card shadow="never">
                  <template #header><strong>总体评估</strong></template>
                  <div class="overview-score">
                    <el-progress type="dashboard" :percentage="assessmentData.overallScore" :color="statusColor">
                      <template #default="{ percentage }">
                        <span class="percentage-value">{{ percentage }}</span>
                        <span class="percentage-label">分</span>
                      </template>
                    </el-progress>
                    <el-tag :type="assessmentData.status.type" size="large" effect="dark">{{ assessmentData.status.text }}</el-tag>
                  </div>
                </el-card>

                <el-card shadow="never" style="margin-top: 20px;">
                  <template #header><strong>分项指标</strong></template>
                  <el-descriptions :column="1" border>
                    <el-descriptions-item label="数据完整率">
                      <el-progress :percentage="assessmentData.completeness.rate" :stroke-width="10" striped />
                    </el-descriptions-item>
                    <el-descriptions-item label="离群点数量">
                      <el-statistic :value="assessmentData.accuracy.outlierCount" />
                    </el-descriptions-item>
                     <el-descriptions-item label="数据标准差">
                      <el-statistic :value="assessmentData.accuracy.stdDev" :precision="4" />
                    </el-descriptions-item>
                    <el-descriptions-item label="数据及时性">
                      <el-tag :type="assessmentData.timeliness.onTime ? 'success' : 'warning'">
                        {{ assessmentData.timeliness.onTime ? '正常' : '有延迟' }}
                      </el-tag>
                    </el-descriptions-item>
                  </el-descriptions>
                </el-card>
              </el-col>

              <el-col :span="17">
                <el-card shadow="never">
                   <template #header><strong>数据时序可视化 (已标记离群点)</strong></template>
                   <div ref="chartRef" style="width: 100%; height: 300px;"></div>
                </el-card>
                
                <el-card shadow="never" style="margin-top: 20px;">
                  <template #header><strong>问题数据明细</strong></template>
                  <el-table :data="assessmentData.issues" border max-height="200">
                    <el-table-column type="index" label="#" width="50" />
                    <el-table-column prop="timestamp" label="时间戳" />
                    <el-table-column prop="value" label="原始值" />
                    <el-table-column prop="type" label="问题类型">
                       <template #default="{ row }">
                        <el-tag :type="row.type === '离群点' ? 'danger' : 'warning'">{{ row.type }}</el-tag>
                       </template>
                    </el-table-column>
                    <el-table-column prop="suggestion" label="处理建议" />
                  </el-table>
                </el-card>
              </el-col>
            </el-row>
          </template>
        </el-skeleton>
      </div>

       <el-empty v-else description="请选择一个数据源开始评估" />
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close">关闭</el-button>
        <el-button type="primary" :disabled="!assessmentData">重新评估</el-button>
        <el-button type="success" :disabled="!assessmentData">导出报告</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, nextTick } from "vue";
import * as echarts from 'echarts';

// --- state ---
const visible = ref<boolean>(false);
const loading = ref<boolean>(false);
const selectedDataSource = ref<string | null>(null);
const assessmentData = ref<any>(null);
const chartRef = ref<HTMLElement | null>(null);
let chartInstance: echarts.ECharts | null = null;

// --- computed ---
const statusColor = computed(() => {
  if (!assessmentData.value) return '#909399';
  const score = assessmentData.value.overallScore;
  if (score >= 90) return '#67c23a'; // success
  if (score >= 70) return '#409eff'; // primary
  if (score >= 50) return '#e6a23c'; // warning
  return '#f56c6c'; // danger
});

// --- methods ---

// 模拟后端处理和返回评估数据
const fetchAssessmentData = (dataSourceId: string) => {
  // 模拟生成时序数据
  const generateData = () => {
    let base = new Date().getTime();
    let data = [];
    for (let i = 24 * 60; i > 0; i--) {
        let now = new Date(base - i * 60000);
        // 模拟一个带有噪声的sin波形，代表位移变化
        let value = Math.sin(i / (24 * 10)) * 2 + Math.random() * 0.5 + 10;
        data.push([now.toISOString(), parseFloat(value.toFixed(4))]);
    }
    // 手动插入几个离群点
    data[100][1] = 15.5; 
    data[800][1] = 5.1;
    return data;
  }
  
  const rawData = generateData();
  const outliers = [
      { timestamp: rawData[100][0], value: rawData[100][1], type: '离群点', suggestion: '建议剔除' },
      { timestamp: rawData[800][0], value: rawData[800][1], type: '离群点', suggestion: '建议剔除' }
  ];

  return {
    overallScore: 85,
    status: { type: 'success', text: '质量良好' },
    completeness: { rate: 99.8 },
    accuracy: { outlierCount: outliers.length, stdDev: 0.2851 },
    timeliness: { onTime: true },
    rawData: rawData,
    issues: outliers
  };
};

// 运行评估
const runAssessment = () => {
  if (!selectedDataSource.value) return;
  loading.value = true;
  assessmentData.value = null;

  setTimeout(() => {
    assessmentData.value = fetchAssessmentData(selectedDataSource.value!);
    loading.value = false;
    // 数据加载后初始化图表
    nextTick(() => {
      initChart();
    });
  }, 1500); // 模拟网络和计算延迟
};

// 初始化 ECharts 图表
const initChart = () => {
  if (!chartRef.value || !assessmentData.value) return;
  
  if (chartInstance) {
      chartInstance.dispose();
  }
  chartInstance = echarts.init(chartRef.value);

  const option = {
    tooltip: { trigger: 'axis' },
    xAxis: { type: 'time' },
    yAxis: { type: 'value', scale: true }, // scale: true 保证不被离群点影响主趋势
    grid: { left: '5%', right: '5%', bottom: '10%' },
    series: [
      {
        name: '原始数据',
        type: 'line',
        showSymbol: false,
        data: assessmentData.value.rawData,
      },
      // 用于标记离群点的系列
      {
        name: '离群点',
        type: 'scatter',
        symbolSize: 15,
        itemStyle: { color: '#f56c6c' },
        data: assessmentData.value.issues.map((issue: any) => [issue.timestamp, issue.value]),
      }
    ]
  };
  
  chartInstance.setOption(option);
};

// --- lifecycle-like hooks ---
const open = () => {
  visible.value = true;
  // 重置状态
  selectedDataSource.value = null;
  assessmentData.value = null;
  if (chartInstance) {
      chartInstance.dispose();
      chartInstance = null;
  }
};

const close = () => {
  visible.value = false;
};

defineExpose({ open, close });
</script>

<style scoped>
.assessment-container {
  min-height: 70vh;
}
.header-controls {
  margin-bottom: 20px;
}
.overview-score {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 15px;
}
.percentage-value {
  font-size: 28px;
  font-weight: bold;
}
.percentage-label {
  font-size: 14px;
  color: #909399;
}
.el-card {
  border: 1px solid var(--el-card-border-color);
}
</style>